package cn.tedu.mall.product.webapi.service.impl;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.pojo.product.dto.CategoryAddNewDTO;
import cn.tedu.mall.common.pojo.product.dto.CategoryUpdateBaseInfoDTO;
import cn.tedu.mall.common.pojo.product.dto.CategoryUpdateFullInfoDTO;
import cn.tedu.mall.common.pojo.product.model.Category;
import cn.tedu.mall.common.pojo.product.vo.CategoryStandardVO;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.product.service.ICategoryService;
import cn.tedu.mall.product.webapi.constant.DataCommonConst;
import cn.tedu.mall.product.webapi.mapper.CategoryAttributeTemplateMapper;
import cn.tedu.mall.product.webapi.mapper.CategoryMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl implements ICategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;
    @Autowired(required = false)
    private CategoryAttributeTemplateMapper categoryAttributeTemplateMapper;

    @Override
    public Long save(CategoryAddNewDTO categoryAddNewDTO) {
        //检查名称是够被使用
        Object checkNameQueryResult = categoryMapper.getByName(categoryAddNewDTO.getName());
        if (checkNameQueryResult != null) {
            throw new CoolSharkServiceException(ResponseCode.CONFLICT, "新增类别失败，类别名称（" + categoryAddNewDTO.getName() + "）已存在！");
        }

        //判断是否有父级类别，没有则视为一级类别
        if (categoryAddNewDTO.getParentId() == null) {
            categoryAddNewDTO.setParentId(0L);
        }
        //检查父级是否存在
        CategoryStandardVO parentCategory = categoryMapper.getById(categoryAddNewDTO.getParentId());
        if (categoryAddNewDTO.getParentId() != 0 && parentCategory == null) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "新增类别失败，父级类别不存在！");
        }

        categoryAddNewDTO.setSort(categoryAddNewDTO.getSort() == null ? DataCommonConst.SORT_DEFAULT : categoryAddNewDTO.getSort());
        Category category = new Category();
        BeanUtils.copyProperties(categoryAddNewDTO, category);

        //补齐depth属性，类别的深度
        int depth = 1;
        if (categoryAddNewDTO.getParentId() != 0) {
            depth = parentCategory.getDepth() + 1;
        }
        category.setDepth(depth);
        category.setParent(0); //新增的类别默认不是父级
        LocalDateTime now = LocalDateTime.now();
        category.setGmtCreate(now);
        category.setGmtModified(now);
        int rows = categoryMapper.insert(category);
        if (rows != 1) {
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "新增类别失败，服务器忙，请稍后再次尝试！");
        }
        return category.getId();
    }

    @Override
    public void deleteById(Long id) {
        //检查尝试删除的类别是否存在
        CategoryStandardVO currentCategory = categoryMapper.getById(id);
        if (currentCategory == null) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "删除类别失败，该类别不存在！");
        }

        //检查尝试删除的类别是否有子级类别
        int childCount = categoryMapper.countByParentId(id);
        if (childCount > 0) {
            throw new CoolSharkServiceException(ResponseCode.CONFLICT, "删除类别失败，该类别存在子级类别！");
        }

        //检查尝试删除的类别是否关联属性模板
        int relationCount = categoryAttributeTemplateMapper.countByCategoryId(id);
        if (relationCount > 0) {
            throw new CoolSharkServiceException(ResponseCode.CONFLICT, "删除类别失败，改类别关联了属性模板!");
        }

        //执行删除
        int rows = categoryMapper.deleteById(id);
        if (rows != 1) {
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "删除类别失败，服务器繁忙，请稍后再次尝试");
        }

        //如果父级类别已经没有其他子级类别，则修改parent_id的值为0
        if (currentCategory.getParentId() != 0) {
            CategoryStandardVO parentCategory = categoryMapper.getById(currentCategory.getParentId());
            if (parentCategory != null) {
                List<?> currentCategorySiblings = categoryMapper.listByParentId(parentCategory.getId());
                if (currentCategorySiblings.size() == 0) {
                    rows = categoryMapper.updateParentById(parentCategory.getId(), 0);
                    if (rows != 1) {
                        throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "删除类别失败，服务器繁忙，请稍后再次尝试");
                    }
                }
            }
        }

    }

    @Override
    public void setEnableById(Long id) {
        //检查该类别是否存在
        CategoryStandardVO currentCategory = categoryMapper.getById(id);
        if (currentCategory == null) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "启动类别失败，该类别不存在！");
        }

        //检查该类别是否已经启动
        if (currentCategory.getEnable().equals(1)) {
            throw new CoolSharkServiceException(ResponseCode.CONFLICT, "启动类别失败，该类别已经启用！");
        }

        //执行更新
        int rows = categoryMapper.updateEnableById(id, 1);
        if (rows !=1){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"启用类别失败，系统繁忙，请稍后再试！");
        }

    }

    @Override
    public void setDisableById(Long id) {
        //检查该类别是否存在
        CategoryStandardVO currentCategory = categoryMapper.getById(id);
        if (currentCategory == null){
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"禁用类别失败，该类别不存在！");
        }

        //检查当前状态是否被禁用
        if (currentCategory.getEnable().equals(0)){
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,"禁用类别失败，该类别已经禁用！");
        }

        //执行更新
        int rows = categoryMapper.updateEnableById(id, 0);
        if (rows != 1){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"禁用类别失败，系统繁忙，请稍后再试！");
        }
    }

    @Override
    public void setDisplayById(Long id) {
        //检查该类别是否存在
        CategoryStandardVO currentCategory = categoryMapper.getById(id);
        if (currentCategory == null){
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"显示类别失败，该类别不存在！");
        }

        //检查该类型是否被显示
        if (currentCategory.getDisplay().equals(1)){
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,"显示类别失败，该类别已经显示！");
        }

        //执行更新
        int rows = categoryMapper.updateDisplayById(id,1);
        if (rows != 1){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"显示类别失败，系统繁忙，请稍后再试！");
        }
    }

    @Override
    public void setHiddenById(Long id) {
        //检查该类别是否存在
        CategoryStandardVO currentCategory = categoryMapper.getById(id);
        if (currentCategory == null){
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"隐藏类别失败，该类别不存在！");
        }

        //检查该类型是否被隐藏
        if (currentCategory.getDisplay().equals(0)){
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,"隐藏类别失败，该类别已经隐藏！");
        }

        //执行更新
        int rows = categoryMapper.updateDisplayById(id,0);
        if (rows != 1){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"隐藏类别失败，系统繁忙，请稍后再试！");
        }
    }

    @Override
    public void updateBaseInfoById(Long id, CategoryUpdateBaseInfoDTO categoryUpdateBaseInfoDTO) {
        //检查该类别是否存在
        CategoryStandardVO currentCategory = categoryMapper.getById(id);
        if (currentCategory == null){
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"更新类别基础信息失败，给类别不存在！");
        }

        //检查新名称是否冲突
        CategoryStandardVO checkNameQueryResult = categoryMapper.getByName(categoryUpdateBaseInfoDTO.getName());
        if (checkNameQueryResult != null && !checkNameQueryResult.getId().equals(id)){
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,"更新类别基础信息失败，类别名称("+categoryUpdateBaseInfoDTO.getName()+")已存在！");
        }

        //执行更新
        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdateBaseInfoDTO,category);
        category.setId(id);
        category.setGmtModified(LocalDateTime.now());
        int rows = categoryMapper.updateBaseInfoById(category);
        if (rows != 1){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"更新类别基础信息失败，系统繁忙，请稍后再试！");
        }
    }

    @Override
    public void updateFullInfoById(Long id, CategoryUpdateFullInfoDTO categoryUpdateFullInfoDTO) {
        //检查该类别是否存在
        CategoryStandardVO currentCategory = categoryMapper.getById(id);
        if (currentCategory == null){
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"更新类别信息失败，给类别不存在！");
        }

        //检查新名称是否冲突
        CategoryStandardVO checkNameQueryResult = categoryMapper.getByName(categoryUpdateFullInfoDTO.getName());
        if (checkNameQueryResult != null && !checkNameQueryResult.getId().equals(id)){
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,"更新类别信息失败，类别名称("+categoryUpdateFullInfoDTO.getName()+")已存在！");
        }

        //执行更新
        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdateFullInfoDTO,category);
        category.setId(id);
        category.setGmtModified(LocalDateTime.now());
        int rows = categoryMapper.updateFullInfoById(category);
        if (rows != 1) {
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "更新类别信息失败，服务繁忙，请稍后再次尝试！");
        }
    }

    @Override
    public CategoryStandardVO getById(Long id) {
        CategoryStandardVO categoryStandardVO = categoryMapper.getById(id);
        if (categoryStandardVO == null){
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"获取类别详情信息失败，该类别不存在！");
        }
        return categoryStandardVO;
    }

    @Override
    public JsonPage<CategoryStandardVO> listByParent(Long parentId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<CategoryStandardVO> categorys = categoryMapper.listByParentId(parentId);
        return JsonPage.restPage(new PageInfo<>(categorys));
    }

    @Override
    public JsonPage<CategoryStandardVO> listByBrand(Long brandId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<CategoryStandardVO> categories = categoryMapper.listByBrandId(brandId);
        return JsonPage.restPage(new PageInfo<>(categories));
    }


}






















